package com.sw.bbs.user.interceptor;

import com.sw.bbs.common.constant.BBSConstant;
import com.sw.bbs.user.service.UserService;
import io.swagger.annotations.Authorization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

import static com.sw.bbs.common.constant.BBSConstant.USERTIMEOUT;

@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private UserService authService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //从header中得到token
        String key = request.getHeader(BBSConstant.ACCESSTOKEN);
        //验证token
        try {

            key = String.format(BBSConstant.ACCESSTOKEN_CACHE_KEY,key);
            String userInfo = redisTemplate.opsForValue().get(key);
            if (userInfo!=null) {
                //如果token验证成功，将token对应的用户id存在request中，便于之后注入
                redisTemplate.opsForValue().set(key,userInfo, USERTIMEOUT, TimeUnit.SECONDS);
                return true;
            }
            //如果验证token失败，并且方法注明了Authorization，返回401错误
            if (method.getAnnotation(Authorization.class) != null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }

        }catch (Exception e) {

        }

        return true;

    }


}
